package P3排序算法;

import java.util.Arrays;

//双路快速排序
public class QuickSort02 {
    public static void main(String[] args) {
        int[] arr = {4, 2, 3, 1, 2, 4, 2, 4, 3, 7, 5, 6, 3, 5, 3, 3, 4, 3, 4, 6, 7, 9, 4, 5, 4};
        quickSort(arr, 0, arr.length - 1);
        System.out.println(Arrays.toString(arr));
    }

    public static void quickSort(int[] arr, int l, int r) {
        if (l >= r) {
            return;
        }
        int p = partition(arr, l, r);
        quickSort(arr, l, p - 1);
        quickSort(arr, p + 1, r);
    }

    public static int partition(int[] arr, int l, int r) {
        swap(arr, l, (int) (Math.random() * (r - l + 1) + l));
        int v = arr[l];
        int j = r;
        int i = l + 1;
        while (true) {
            while (i <= r && arr[i] <= v) {
                i++;
            }
            while (j >= l + 1 && arr[j] >= v) {
                j--;
            }
            if (i > j) {
                break;
            }
            swap(arr, i, j);
            i++;
            j--;
        }
        swap(arr, l, j);
        return j;
    }

    private static void swap(int[] arr, int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }
}